<template>
  <div ref="chartDom" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { getCurrentInstance } from 'vue'

const props = defineProps({
  options: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  },
  autoResize: {
    type: Boolean,
    default: true
  }
})

const chartDom = ref(null)
let chart = null
const { proxy } = getCurrentInstance()

// 初始化图表
const initChart = () => {
  if (!chartDom.value) return
  chart = proxy.$echarts.init(chartDom.value)
  chart.setOption(props.options)
}

// 监听窗口大小变化
const handleResize = () => {
  if (chart && props.autoResize) {
    chart.resize()
  }
}

// 监听options变化
watch(
  () => props.options,
  (newOptions) => {
    if (chart) {
      chart.setOption(newOptions)
    }
  },
  { deep: true }
)

onMounted(() => {
  initChart()
  if (props.autoResize) {
    window.addEventListener('resize', handleResize)
  }
})

onBeforeUnmount(() => {
  if (props.autoResize) {
    window.removeEventListener('resize', handleResize)
  }
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
div {
  box-sizing: border-box;
}
</style>
